﻿using LoveEatRabbit.API.Write.Applications.Commands.Roles;
using LoveEatRabbit.Domain.RBAC;
using LoveEatRabbit.ErrorCode;
using LoveEatRabbit.Infrastructure.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore.Metadata;

namespace LoveEatRabbit.API.Write.Applications.CommandHandlers.Roles
{
    public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, APIResult<int>>
    {
        private readonly IBaseRespository<RoleModel> roleRep;
        private readonly IBaseRespository<RolePermissionModel> roleperRep;

        public AddRoleCommandHandler(IBaseRespository<RoleModel> roleRep, 
            IBaseRespository<RolePermissionModel> roleperRep)
        {
            this.roleRep = roleRep;
            this.roleperRep = roleperRep;
        }

        public async Task<APIResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result=new APIResult<int>();
            result.Code=APIResultCode.添加成功;
            result.Message=APIResultCode.添加成功.ToString();

            RoleModel role=new RoleModel();
            role.RoleName=request.RoleName;
            role.States = true;
            role.IsDeleted = false;
            role.CreatedTime = DateTime.UtcNow;
            await roleRep.AddAsync(role);

            //添加角色权限中间件
            var list=new List<RolePermissionModel>();
            foreach (var item in request.PermissionId)
            {
                list.Add(new RolePermissionModel()
                {
                    RoleId=role.RoleId,
                    PermissionId=item
                });
            }
            await roleperRep.AddRange(list);





            return await Task.FromResult(result);
        }
    }
}
